
package com.epam.android.training.day7.task1;

import android.app.Service;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Local android service which generates random payload and sends it to
 * broadcast reviever with a configured period.
 * 
 * @author Anton Novikau
 */
public class SimpleService extends Service {

  private static final Random GEN = new Random();

  private final LocalBinder binder = new LocalBinder();

  private Timer job;

  /** Return the communication channel to the service. */
  @Override
  public IBinder onBind(Intent intent) {

    return binder;
  }

  /** Called by the system when the service is first created. */
  @Override
  public void onCreate() {
    super.onCreate();
    job = new Timer("Random generator job");
    Resources resources = getResources();
    int delay = resources.getInteger(R.integer.job_delay_in_sec) * 1000;
    int period = resources.getInteger(R.integer.job_period_in_sec) * 1000;

    // start periodical job which notifies broadcast reciever.
    job.schedule(new ServiceJob(), delay, period);
    Toast.makeText(this, R.string.service_started_message, Toast.LENGTH_SHORT).show();
  }

  @Override
  public void onDestroy() {
    job.cancel();
    Toast.makeText(this, R.string.service_stopped_message, Toast.LENGTH_SHORT).show();
    super.onDestroy();
  }

  /**
   * Periodical task which sends notification to broadcast reciever with
   * randomly generated integer payload.
   * 
   * @author Anton Novikau
   */
  private class ServiceJob extends TimerTask {

    @Override
    public void run() {
      int value = GEN.nextInt();
      Intent intent = new Intent(SimpleService.this, ServiceInteractionReciever.class);
      intent.putExtra(getText(R.string.random_number_bundle_key).toString(), value);
      sendBroadcast(intent);
    }
  }

  /**
   * Class for clients to access. Because we know this service always runs in
   * the same process as its clients, we don't need to deal with IPC.
   */
  public class LocalBinder extends Binder {
    SimpleService getService() {
      return SimpleService.this;
    }
  }
}
